package net.asfun.jvalog.action;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;

import javax.script.Bindings;
import javax.script.SimpleBindings;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import net.asfun.jvalog.http.RequestUtil;
import net.asfun.jvalog.misc.Setting;
import net.asfun.jvalog.service.Painter;
import static net.asfun.jvalog.misc.Log.logger;

abstract public class BaseAction {
	
	protected Bindings data;
	private static final Properties prop; 
	
	static {
		prop = new Properties();
		try {
			prop.load(new FileInputStream(Setting.root + "/WEB-INF/classes/interact.properties"));
		} catch (IOException e) {
			logger.log(Level.SEVERE, "properties read error", e.getCause());
		}
	}
	
	public BaseAction() {
		data = new SimpleBindings();	
	}
	
	protected void assign(String key, Object value){
		if ( value != null ) {
			data.put(key, value);
		} else {
			data.remove(key);
		}
	}
	
	protected String getMessage(String key) {
		return prop.getProperty(key + ".message");
	}
	
	protected String getForward(String key) {
		return prop.getProperty(key + ".forward");
	}
	
	protected void feedback(String key, HttpServletRequest req, HttpServletResponse resp) throws IOException {
		if ( RequestUtil.isAjaxRequest(req) ) {
			tip(key, resp);
		} else {
			assign("message", getMessage(key));
			assign("forward", getForward(key));
			render("admin/tip.html", resp);
		}
	}
	
	protected void feedfront(String key, HttpServletRequest req, HttpServletResponse resp) throws IOException {
		if ( RequestUtil.isAjaxRequest(req) ) {
			tip(key, resp);
		} else {
			assign("message", getMessage(key));
			assign("forward", getForward(key));
			render("tip.html", resp);
		}
	}

	protected void render(String path, HttpServletResponse resp) throws IOException {
//		ThreadHelper.header().setHeaders(resp);
		resp.setCharacterEncoding("utf-8");
		resp.getWriter().write(Painter.render(path, data));
	}
	
	protected void tip(String key, HttpServletResponse resp) throws IOException {
//		ThreadHelper.header().setCache(0);
//		ThreadHelper.header().setMime("text/plain");
//		ThreadHelper.header().setHeaders(resp);
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("utf-8");
		resp.setHeader("Cache-Control","no-store");
		resp.setHeader("Pragma","no-cache");
		resp.setDateHeader("Expires", 0);
		String message = null;
		try {
			JSONObject json = new JSONObject();
			json.put("type", "info");
			json.put("message", getMessage(key));
			message = json.toString();
		} catch (JSONException e) {
			message = "{type:\"error\",message:\"json error\"}";
			logger.log(Level.SEVERE, e.getMessage(), e);
		}
		resp.getWriter().write(message);
	}
}
